package com.hejing.Java比较器;

/**
 * ClassName: Product
 * Package: com.hejing.Java比较器.Comparable
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-04-17 21:04
 * @Version: 1.0
 */
public class Product implements Comparable{

    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public Product() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    /**
     *
     * 当前类需要实现Comparable中的抽象方法 compareTo()
     * 在此方法中指明如何判断当前类的对象的大小，
     *
     * 如果返回值是正数, 当前对象大
     * 如果返回值是负数, 当前对象小
     * 如果返回值是0, 一样大
     * @param o the object to be compared.
     * @return
     */
//    @Override
//    public int compareTo(Object o) {
//        if (o == this) {
//            return 0;
//        }
//        if (o instanceof Product) {
//            Product p = (Product) o;
//            return Double.compare(this.price, p.price);
//        }
//
//        throw new RuntimeException("类型不匹配");
//    }


    // 比较标准: 先比较价格，价格相同，进行名字的比较(从小到大)
    @Override
    public int compareTo(Object o) {
        if (o == this) {
            return 0;
        }
        if (o instanceof Product) {
            Product p = (Product) o;
            int value = Double.compare(this.price, p.price);
            if (value != 0) {
                return value;
            }
            return this.name.compareTo(p.name);
        }

        throw new RuntimeException("类型不匹配");
    }
}





















